package com.tz.fruit.service.impl;

import com.tz.fruit.entity.OrderItem;
import com.tz.fruit.service.IProductService;
import com.tz.fruit.service.IShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by Tyranty on 2017/7/20 0020.
 */
@Service
public class ShoppingCartImpl implements IShoppingCart {

    @Autowired
    private IProductService productService;
    //属性
    private Map<Long, OrderItem> items = new HashMap<>();//购物车商品集合
    private double total;//总费用

    @Override
    public void saveCart(OrderItem orderItem) {
        if (orderItem!=null){
            items.put(productService.findByPNo(orderItem.getpNo()).getPid(),orderItem);
            updateTotal();
        }
    }

    @Override
    public void clear() {
        items.clear();
        updateTotal();
    }

    @Override
    public void modifyCount(Long pid, int count) {
         OrderItem item =items.get(pid);
         item.setCount(count);
//         item.setTotal(count*item.getPrice());
         updateTotal();
    }

    @Override
    public void delete(Long pid) {
        if (pid!=null){
            items.remove(pid);
            updateTotal();
        }
    }

    @Override
    public double getTotal() {
        return total;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Map<Long, OrderItem> getItems() {
        return items;
    }

    @Override
    public OrderItem find(Long pid) {
        return items.get(pid);
    }

    private void updateTotal() {
        Set<Long> item = items.keySet();
        Iterator<Long> iterator = item.iterator();
        double it = 0;
        while (iterator.hasNext()) {
            Long next = iterator.next();
            OrderItem item1 = items.get(next);
            //保留一位小数
//            BigDecimal b = new BigDecimal(item1.getPrice() * item1.getCount());
//            it += b.setScale(1, BigDecimal.ROUND_DOWN).doubleValue();

            it+=item1.getPrice() * item1.getCount();
            it = Double.parseDouble(String.format("%.1f",it));
        }
        this.total = it;
    }
}
